package com.github.admin.edu.security.jwt.client.interceptor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.github.admin.edu.assembly.common.entity.JsonEntity;
import com.github.admin.edu.assembly.common.util.JsonUtils;
import com.github.admin.edu.assembly.exception.auth.ClientTokenException;
import com.github.admin.edu.assembly.string.util.StringUtils;
import com.github.admin.edu.oauth.server.api.entity.TokenEntity;
import com.github.admin.edu.security.jwt.client.domain.ServiceClientAuthDomain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Create by IntelliJ IDEA
 * 用户：王建
 * 日期：2018-7-18
 */
public class ServiceResultAuthInterceptor extends HandlerInterceptorAdapter {

    /**
     * 自定义请求头信息
     * 用于获取token信息
     */
    @Value("${server.custom.token.header.token-header}")
    private String tokenHeader;
    @Value("${server.custom.token.header.client-id}")
    private String clientId;
    @Value("${server.custom.server.server-id}")
    private String serverId;
    @Autowired
    private ServiceClientAuthDomain domain;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //TODO 后期添加自定义注解，使用改注解的请求，不进行token验证
        //配置该注解，说明不进行服务拦截
        /*
         HandlerMethod handlerMethod = (HandlerMethod) handler;
        IgnoreClientToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreClientToken.class);*/
        /*if (annotation == null) {
            annotation = handlerMethod.getMethodAnnotation(IgnoreClientToken.class);
        }
        if(annotation!=null) {
            return super.preHandle(request, response, handler);
        }*/
        String token = request.getHeader(tokenHeader);//获取请求头信息中的token值
        String client_id=request.getHeader(clientId);//请求头信息中的clientId值
        if(StringUtils.isNotBlank(token)){
            String info=domain.authToken(client_id,serverId,token);
            if(StringUtils.isNotBlank(info)){
                JsonEntity<TokenEntity> jsonEntity=JsonUtils.toCollection(info, new TypeReference<JsonEntity<TokenEntity>>() {});
                if(null!=jsonEntity&&jsonEntity.getState()==200){//有权限
                    return true;
                }
                throw new ClientTokenException("token 校验失败，没有权限访问！");
            }
        }
       throw  new ClientTokenException("token is not find !!!!!! ");
    }
}
